import type { RendererArchivesInvoker } from "@common/ipc-types.ts";
import type { UnzipCompleteArgs, UnzipErrorArgs, UnzipFileArgs } from "@common/archives-file-types.ts";
import { ipcInvoker } from "./electron.ts";

export const archivesInvoker: RendererArchivesInvoker = {
  unzip(args: UnzipFileArgs): Promise<UnzipCompleteArgs> {
    return new Promise<UnzipCompleteArgs>(async (resolve, reject) => {
      ipcInvoker.send("archives.unzip", args);
      const id = args.id;

      const onUnzipError = (args: UnzipErrorArgs) => {
        reject(`解压失败: ${args.message}`);
        unsubscribe();
      };
      const onUnzipComplete = (args: UnzipCompleteArgs) => {
        resolve(args);
        unsubscribe();
      };

      const id0 = ipcInvoker.on(`unzip.error.${id}`, onUnzipError);
      const id1 = ipcInvoker.on(`unzip.complete.${id}`, onUnzipComplete);

      function unsubscribe() {
        ipcInvoker.off(`unzip.error.${id}`, id0);
        ipcInvoker.off(`unzip.complete.${id}`, id1);
      }
    });
  },
  cancelUnzip(id: string): void {
    ipcInvoker.send("archives.unzip.cancel", id);
  },
};
